﻿#include "CenterWidget.h"

#include <QHBoxLayout>
#include <QStandardItemModel>
#include <QLabel>
#include <QVBoxLayout>
#include <QMenu>
#include <QHeaderView>

#include "ElaPushButton.h"
#include "ElaScrollPageArea.h"
#include "ElaTabWidget.h"
#include "ElaScrollBar.h"
#include "ElaTreeView.h"
#include "ElaText.h"

#include "ThreeDimensionDiagraph.h"
#include "BaseModule/IBaseSignal.h"

#include "qcustomplot.h"
#include "Graph2D.h"
#include "Graph3D.h"
#include "GraphSurface.h"
#include "ElaTheme.h"
#include "TextFileParser.h"

namespace pst
{

    CenterWidget::CenterWidget(QWidget* parent)
        : T_BasePage(parent)
    {
        // 设置窗口布局
        setContentsMargins(0, 8, 0, 0);
        QWidget* centralWidget = new QWidget(this);
        QHBoxLayout* centerVLayout = new QHBoxLayout(centralWidget);
        centerVLayout->setContentsMargins(0, 0, 0, 0);
        centerVLayout->setSpacing(8);




        // ------------------ 后处理窗口的选项卡视图
        m_tabWidget = new ElaTabWidget(this);
        m_tabWidget->setObjectName("ElaTabWidget");
        m_tabWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding);
        // 创建二维视图
        //_graph2D = new Graph2D(m_tabWidget);
        //m_tabWidget->addTab(_graph2D, "图1");
        // 创建三维视图
        //auto _threeDimensionDiagraph = new pst::ThreeDimensionDiagraph(this);
        //m_tabWidget->addTab(_threeDimensionDiagraph, "图2");

        // ------------------ 项目树
        //创建项目树的模型
        QStandardItemModel* model = new QStandardItemModel();
        QStandardItem* _itemParent = new QStandardItem(QString("工程1"));
        _itemParent->setCheckable(false);
        model->appendRow(_itemParent);
        //for (int i = 0; i < 5; i++)
        //{
        //    QStandardItem* _itemParent = new QStandardItem(QString("工程%1").arg(i));
        //    _itemParent->setCheckable(false);
        //    for (int j = 0; j < 6; j++)
        //    {
        //        QStandardItem* _itemChild = new QStandardItem(QString("数据%1").arg(i));
        //        _itemChild->setCheckable(false);
        //        _itemParent->appendRow(_itemChild);
        //    }
        //    model->appendRow(_itemParent);
        //    model->item(0)->appendRow(new QStandardItem(QString("数据")));
        //}
        model->setHeaderData(0, Qt::Horizontal, "数据展示", Qt::DisplayRole);

        m_treeView = new ElaTreeView(this);
        //设置滚动条
        ElaScrollBar* treeViewFloatScrollBar = new ElaScrollBar(m_treeView->verticalScrollBar(), m_treeView);
        treeViewFloatScrollBar->setIsAnimation(true);
        //设置标题
        QFont headerFont = m_treeView->header()->font();
        headerFont.setPixelSize(16);
        m_treeView->header()->setFont(headerFont);
        m_treeView->setModel(model);
        m_treeView->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Expanding);
        m_treeView->expandAll();

        // 连接信号与槽  
        connect(m_treeView, &QTreeView::customContextMenuRequested, this, &CenterWidget::showContextMenu);
        m_treeView->setContextMenuPolicy(Qt::CustomContextMenu); // 设置上下文菜单策略  


        connect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, [this]()
            {auto indexs = getSelectedItems(); emit signal_fileClicked(indexs); });
        //将项目树和后处理窗口添加到中间视图
        QSplitter* splitter = new QSplitter(Qt::Horizontal, centralWidget);
        //splitter->setContentsMargins(0, 0, 0, 0);
        splitter->addWidget(m_treeView);
        splitter->addWidget(m_tabWidget);
        splitter->setSizes({ 100,600 });
        centerVLayout->addWidget(splitter);
        addCentralWidget(centralWidget, true, false, 0);
    }

    CenterWidget::~CenterWidget()
    {
        //for (auto i : m_graph2DList)
        //{
        //    if (i != nullptr)
        //    {
        //        delete i;
        //        i = nullptr;
        //    }
        //}
    }

    QWidget* CenterWidget::getCurrentGraphWindow()
    {
        return  m_tabWidget->currentWidget();
    }

    void CenterWidget::setCurrentGraphWindow(QWidget* currentW)
    {
        m_tabWidget->setCurrentWidget(currentW);
    }

    void CenterWidget::showContextMenu(const QPoint& pos)
    {
        QModelIndex index = m_treeView->indexAt(pos);
        // 检查是否点击在有效的行上  
        if (!index.isValid()) {
            return; // 如果没有有效索引，则不显示菜单  
        }

        auto model = (QStandardItemModel*)m_treeView->model();
        QStandardItem* item = model->itemFromIndex(index);

        if (item && (item->parent() == nullptr))
        {
            return; // 如果不是叶子节点，则不显示菜单  
        }

        // 获取上下文菜单的位置  
        QMenu contextMenu;

        // 创建“添加到当前图”选项  
        QAction* addAction = contextMenu.addAction("添加到当前图");
        connect(addAction, &QAction::triggered, this, &CenterWidget::addToCurrentGraph);

        contextMenu.exec(m_treeView->viewport()->mapToGlobal(pos));
    }

    void CenterWidget::addToCurrentGraph()
    {
        emit signal_addToCurrentGraph(getSelectedItems());
    }

    void CenterWidget::addFileNode(QStandardItem* item)
    {
        auto model = (QStandardItemModel*)m_treeView->model();
        model->item(0)->appendRow(item);
    }

    QList<QStandardItem*> CenterWidget::getSelectedItems()
    {
        QList<QStandardItem*> selectedItems;
        QModelIndexList indexes = m_treeView->selectionModel()->selectedIndexes();
        for (const QModelIndex& index : indexes)
        {
            auto model = (QStandardItemModel*)m_treeView->model();
            selectedItems.append(model->itemFromIndex(index));
        }
        return selectedItems;
    }

    //void CenterWidget::slot_fileClicked(const QModelIndex& index)
    //{
    //    emit
    //}
    //void CenterWidget::addNewProject()
    //{
    //}

    void CenterWidget::addLineToGrapg2D(Graph2D* _graph2D,
        const QPair<QString, QVector<double>>& x,
        const QPair<QString, QVector<double>>& y)
    {
        _graph2D->addLine(x, y);
    }

    void CenterWidget::addLineToGrapg2D(InfomationCurve2DBasical& info)
    {
        if (info.getGraph() == nullptr)
        {
            return;
        }
        auto curAddress = info.getGraph()->addLine(info);
        info.setCurveLineAddress(curAddress);
    }

    void CenterWidget::addLinesToNewGrapg2DWindow(QList<InfomationCurve2DBasical>& infos, bool useNewWindow)
    {
        Graph2D* graph{ nullptr };
        if (useNewWindow)
        {
            graph = addNewGraph2D();
        }
        else
        {
            graph = qobject_cast<Graph2D*>(m_tabWidget->currentWidget());
        }
        if (graph == nullptr)
        {
            emit IBaseSignalInstance->signal_sendErrorMessageToUI("图像类型不匹配");
            return;
        }

        const auto& curveMap = graph->getCurve();
        if (!curveMap.isEmpty()) {
            const auto& value = curveMap.begin().value();
            const auto& str = value.getReader()->getEachColNameOfKey().at(value.getScanParameterIndex());
            for (auto i : infos) {
                if (str != i.getReader()->getEachColNameOfKey().at(i.getScanParameterIndex())) {
                    emit IBaseSignalInstance->signal_sendErrorMessageToUI("数据变量不一致，请重新选择工程文件");
                    return;
                }
            }
        }

        for (auto i : infos)
        {
            i.setGraph(graph);
            addLineToGrapg2D(i);
        }
        if (m_isActiveAuto)
        {
            m_tabWidget->setCurrentWidget(graph);
        }
    }

    void CenterWidget::slot_addLinesToNewGrapg2DWindow(QList<InfomationCurve2DBasical>& infos)
    {
        addLinesToNewGrapg2DWindow(infos, true);
    }


    bool CenterWidget::saveScreenShot(const QString& path)
    {
        //return _graph2D->saveScreenShot(path);
        QWidget* currentGraph = m_tabWidget->currentWidget();
        if (qobject_cast<Graph2D*>(currentGraph) != nullptr)
        {
            return qobject_cast<Graph2D*>(currentGraph)->saveScreenShot(path);
        }
        else if (qobject_cast<Graph3D*>(currentGraph) != nullptr)
        {
            return qobject_cast<Graph3D*>(currentGraph)->saveScreenShot(path);
        }
        else if (qobject_cast<GraphSurface*>(currentGraph) != nullptr)
        {
            return qobject_cast<GraphSurface*>(currentGraph)->saveScreenShot(path);
        }

        return false;
    }

    void CenterWidget::setAddedGraphWindowActiveAuto(bool activeAuto)
    {
        m_isActiveAuto = activeAuto;
    }

    bool CenterWidget::getAddedGraphWindowActiveAuto()
    {
        return m_isActiveAuto;
    }

    Graph2D* CenterWidget::addNewGraph2D()
    {
        Graph2D* graph = new Graph2D(this);
        m_graph2DList.append(graph);
        m_graph2DCount++;
        m_tabWidget->addTab(graph, QString::number(m_graph2DCount));
        connect(graph, &Graph2D::signal_generateANewGraphCurve, this, &CenterWidget::slot_addLinesToNewGrapg2DWindow);
        return graph;
    }

    Graph3D* CenterWidget::addNewGraph3D()
    {
        Graph3D* graph = new Graph3D(this);
        m_graph3DList.append(graph);
        m_graph2DCount++;
        m_tabWidget->addTab(graph, QString::number(m_graph2DCount));
        return graph;
    }

    GraphSurface* CenterWidget::addNewGraphSurface()
    {
        GraphSurface* graph = new GraphSurface(this);
        //m_graph3DList.append(graph);
        m_graph2DCount++;
        m_tabWidget->addTab(graph, QString::number(m_graph2DCount));
        return graph;
    }

    void CenterWidget::addImageToNewGraph3DWindow(QList<InfomationGraph3DBasical>& infos, bool useNewWindow)
    {
        Graph3D* graph{ nullptr };

        if (useNewWindow)
        {
            graph = addNewGraph3D();
        }
        else
        {
            graph = qobject_cast<Graph3D*>(m_tabWidget->currentWidget());
        }
        if (graph == nullptr)
        {
            emit IBaseSignalInstance->signal_sendErrorMessageToUI("图像类型不匹配");
            return;
        }

        for (auto& i : infos)
        {
            i.m_graph = graph;
            addImageToGraph3D(i);
        }
        if (m_isActiveAuto)
        {
            m_tabWidget->setCurrentWidget(graph);
        }
    }

    void CenterWidget::addImageToGraph3D(InfomationGraph3DBasical& info)
    {
        if (info.m_graph == nullptr)
        {
            return;
        }
        info.m_graph->addGraph3D(info);
    }

    void CenterWidget::addImageToNewSurfaceWindow(const QString& fileName)
    {
        GraphSurface* graph = addNewGraphSurface();
        if (m_isActiveAuto)
        {
            m_tabWidget->setCurrentWidget(graph);
        }
        graph->addSurfaceActor(fileName);
    }

    void CenterWidget::addPropToGraph3D(Graph3D* graph, QList<vtkProp*> props)
    {
        graph->addProp(props);
    }

    //void CenterWidget::setCurrentTab(Graph2D* _graph2D)
    //{
    //    m_tabWidget->setCurrentWidget(_graph2D);
    //}

}
